<template>
  <div class="guide-detail">
    <!-- 骨架屏：内容未加载时显示骨架屏，加载后显示真实内容 -->
    <t-skeleton
      :loading="loading"
      animation="flashed"
      :row-col="[
        { type: 'text', width: '60%' },
        { type: 'text', width: '40%' },
        { type: 'rect', height: '180px' },
      ]"
    >
      <div class="guide-header">
        <h2 class="guide-title">{{ detail.title }}</h2>
        <div v-if="detail.subtitle" class="guide-subtitle">{{ detail.subtitle }}</div>
      </div>

      <!-- 发布信息：发布人、发布时间和创建时间 -->
      <div class="guide-publish-info">
        <div class="create-time">提交审核时间：{{ detail.createTime }}</div>
        <div class="publish-time" v-show="detail.isCheck === 2">发布时间：{{ detail.publishTime }}</div>
        <div class="publish-author">发布人：{{ detail.publisher || '未知' }}</div>
      </div>

      <!-- 内容 -->
      <!-- <div class="guide-content" v-html="detail.content"></div> -->
      <div class="rich-text-demo">
        <div class="demo-phone">
          <!-- 手机壳图片 -->
          <img src="@/assets/phone.png" class="phone-frame-img" />
          <!-- 屏幕内容区域 -->
          <div class="demo-phone-content">
            <iframe
              ref="iframeRef"
              id="demo-modal"
              scrolling="auto"
              frameborder="0"
              src="https://parse.slovej.icu/"
              class="iframe"
              style="width: 100%; height: 100%"
            ></iframe>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="guide-btns" v-if="from === 'GuideSimpleList'">
        <t-button theme="primary" @click="confirm" v-if="detail.isCheck === 0">确认</t-button>
        <t-button theme="primary" @click="handleModifyReason" v-if="detail.isCheck === 1">修改原因</t-button>
        <t-button theme="danger" @click="handleReject" v-if="detail.isCheck === 0" style="margin-left: 20px"
          >打回</t-button
        >
        <t-button @click="handleBack" style="margin-left: 20px">返回</t-button>
      </div>
      <div class="guide-btns" v-else>
        <t-button theme="primary" @click="handleEdit">编辑</t-button>
        <t-button @click="handleBack" style="margin-left: 20px">返回</t-button>
      </div>
    </t-skeleton>

    <!-- 打回对话框 -->
    <t-dialog
      v-model:visible="showRejectDialog"
      header="打回指南"
      :on-confirm="confirmReject"
      :on-cancel="cancelReject"
      confirm-btn="确认"
      cancel-btn="取消"
    >
      <div style="padding: 16px">
        <div style="margin-bottom: 8px; color: var(--td-text-color-primary)">请填写打回原因：</div>
        <t-textarea
          v-model="rejectReason"
          placeholder="请输入打回原因（必填，最多250字）"
          :maxlength="250"
          :autosize="{ minRows: 6, maxRows: 8 }"
          style="width: 100%"
        />
      </div>
    </t-dialog>

    <!-- 修改原因对话框 -->
    <t-dialog
      v-model:visible="showModifyReasonDialog"
      header="修改打回原因"
      :on-confirm="confirmModifyReason"
      :on-cancel="cancelModifyReason"
      confirm-btn="确认"
      cancel-btn="取消"
    >
      <div style="padding: 16px">
        <div style="margin-bottom: 8px; color: var(--td-text-color-primary)">请修改打回原因：</div>
        <t-textarea
          v-model="modifyReason"
          placeholder="请输入打回原因（必填，最多250字）"
          :maxlength="250"
          :autosize="{ minRows: 6, maxRows: 8 }"
          style="width: 100%"
        />
      </div>
    </t-dialog>
  </div>
</template>

<script setup>
import { getGuideDetail, updateGuide } from '@/api/guide';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { nextTick, onActivated, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 定义响应式变量存储详情数据
const detail = ref({});
// 定义loading变量，控制骨架屏显示
const loading = ref(true);

// 打回相关的响应式变量
const rejectReason = ref('');
const showRejectDialog = ref(false);

// 修改原因相关的响应式变量
const modifyReason = ref('');
const showModifyReasonDialog = ref(false);

// 获取路由和路由参数
const route = useRoute();
const router = useRouter();

// 接收查询的指南详情
const guideDetail = ref({});

// 获取来源
const from = useRoute().query.from;

// 获取iframeRef
const iframeRef = ref();

// 发送内容到iframe预览
const sendContentToIframe = async (html) => {
  // 等待 DOM 更新完成
  await nextTick();

  // 添加延迟确保 iframe 已加载
  setTimeout(() => {
    try {
      console.log('iframeRef.value', iframeRef.value);
      if (iframeRef.value) {
        console.log('iframeRef.value.contentWindow', iframeRef.value.contentWindow);
        if (iframeRef.value.contentWindow) {
          console.log('iframeRef.value.contentWindow', iframeRef.value.contentWindow);
          // 使用 postMessage 发送 HTML 到 iframe
          iframeRef.value.contentWindow.postMessage(
            { type: 'UPDATE_CONTENT', html }, // 消息格式
            '*', // 目标 origin（* 表示任何，生产环境应指定具体域名）
          );
        } else {
          console.warn('iframe contentWindow 不可用');
        }
      } else {
        console.warn('iframeRef 未定义或为空');
      }
    } catch (error) {
      console.error('发送内容到 iframe 时出错:', error);
    }
  }, 300); // 延迟 300ms 确保 iframe 加载完成
};

onMounted(() => {
  // 监听iframe的message事件
  window.addEventListener('message', (event) => {
    console.log('message', event);
  });
  console.log('onMounted');
});

// 页面加载时获取详情
onActivated(async () => {
  console.log('onActivated');
  loading.value = true;
  // 获取id参数并转换为数字类型
  const id = Number(route.query.id);
  // 调用接口获取详情
  const res = await getGuideDetail(id);
  // 获取数据
  guideDetail.value = res.data.data;
  // 字段映射，将createTime赋值给publishTime，同时保留createTime
  detail.value = {
    ...guideDetail.value,
    publishTime: guideDetail.value.updateTime,
  };
  loading.value = false; // 加载完成，隐藏骨架屏

  if (detail.value.content) {
    await sendContentToIframe(detail.value.content);
  }

  // 组件挂载时修改指南状态为已读
  if (route.query.isRead === '0') {
    updateGuide({ id: route.query.id, isRead: 1 });
  }
});

// 编辑按钮点击事件
const handleEdit = () => {
  // 跳转到GuideAdd页面，并带上id参数
  router.push({ name: 'GuideAdd', query: { id: detail.value.id } });
};

// 确认按钮点击事件
const confirm = async () => {
  const dialogInstance = DialogPlugin.confirm({
    header: '提示',
    body: '确认要使该指南通过审核吗？',
    onConfirm: async () => {
      try {
        await updateGuide({ id: detail.value.id, isCheck: 2 });
        MessagePlugin.success('审核通过');
        dialogInstance.destroy();
        // 跳转到GuideSimpleList页面，并带上categoryId、categoryName
        router.push({
          name: 'GuideSimpleList',
          query: {
            categoryId: guideDetail.value.categoryId,
            categoryName: guideDetail.value.categoryName,
            activeTab: route.query.activeTab,
          },
        });
      } catch (error) {
        MessagePlugin.error(error.message || '审核失败');
      }
    },
  });
};

// 打回按钮点击事件
const handleReject = () => {
  // 显示打回对话框
  showRejectDialog.value = true;
};

// 修改原因按钮点击事件
const handleModifyReason = () => {
  // 回显原有的打回原因
  modifyReason.value = detail.value.rejectReason || '';
  // 显示修改原因对话框
  showModifyReasonDialog.value = true;
};

// 验证打回原因
const validateReason = (value) => {
  if (!value || value.trim() === '') {
    return '打回原因不能为空';
  }
  if (value.length > 250) {
    return '打回原因不能超过250字';
  }
  return '';
};

// 确认打回
const confirmReject = async () => {
  const errorMsg = validateReason(rejectReason.value);
  if (errorMsg) {
    MessagePlugin.warning(errorMsg);
    return;
  }

  try {
    await updateGuide({
      id: detail.value.id,
      isCheck: 1,
      rejectReason: rejectReason.value.trim(),
    });
    MessagePlugin.success('指南已打回');
    showRejectDialog.value = false;
    rejectReason.value = '';
    // 跳转到GuideSimpleList页面，并带上categoryId、categoryName
    router.push({
      name: 'GuideSimpleList',
      query: {
        categoryId: guideDetail.value.categoryId,
        categoryName: guideDetail.value.categoryName,
        activeTab: route.query.activeTab,
      },
    });
  } catch (error) {
    MessagePlugin.error(error.message || '打回失败');
  }
};

// 取消打回
const cancelReject = () => {
  showRejectDialog.value = false;
  rejectReason.value = '';
};

// 确认修改原因
const confirmModifyReason = async () => {
  const errorMsg = validateReason(modifyReason.value);
  if (errorMsg) {
    MessagePlugin.warning(errorMsg);
    return;
  }

  try {
    await updateGuide({
      id: detail.value.id,
      isCheck: 1,
      rejectReason: modifyReason.value.trim(),
    });
    MessagePlugin.success('打回原因已修改');
    showModifyReasonDialog.value = false;
    modifyReason.value = '';
    // 跳转到GuideSimpleList页面，并带上categoryId、categoryName
    router.push({
      name: 'GuideSimpleList',
      query: {
        categoryId: guideDetail.value.categoryId,
        categoryName: guideDetail.value.categoryName,
        activeTab: route.query.activeTab,
      },
    });
  } catch (error) {
    MessagePlugin.error(error.message || '修改打回原因失败');
  }
};

// 取消修改原因
const cancelModifyReason = () => {
  showModifyReasonDialog.value = false;
  modifyReason.value = '';
};

// 返回按钮点击事件
const handleBack = () => {
  // 根据来源页面进行返回
  if (from === 'guide') {
    router.push({ name: 'GuideIndex' });
  } else if (from === 'guideline') {
    // 返回时传递tab参数，保持tab状态
    const tab = route.query.tab || 'unread'; // 如果没有tab参数，默认使用unread
    router.push({
      name: 'GuideLine',
      query: { tab },
    });
  } else if (from === 'GuideSimpleList') {
    router.push({
      name: 'GuideSimpleList',
      query: {
        categoryId: guideDetail.value.categoryId,
        categoryName: guideDetail.value.categoryName,
        activeTab: route.query.activeTab,
      },
    });
  }
};
</script>

<style scoped>
.guide-detail {
  max-width: 600px;
  margin: 0 auto;
  border-radius: var(--td-radius-large);
  box-shadow: var(--td-shadow-1);
  padding: 32px 32px 24px 32px;
  min-height: 400px;
}

.guide-header {
  text-align: center;
  margin-bottom: 18px;
}

.guide-title {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 0.5em;
  line-height: 1.2;
  color: var(--td-text-color-primary);
  word-wrap: break-word; /* 允许长单词换行 */
  word-break: break-all; /* 强制换行 */
  max-width: 100%; /* 最大宽度限制 */
  text-align: center; /* 确保居中对齐 */
}

.guide-subtitle {
  font-size: 1.25rem;
  color: var(--td-text-color-secondary);
  font-weight: 500;
  margin-top: 0.2em;
  margin-bottom: 0.5em;
  line-height: 1.3;
}

.guide-publish-info {
  display: flex;
  flex-direction: column; /* 改为竖着排列 */
  align-items: center; /* 居中对齐 */
  margin-bottom: 28px;
  padding: 0 20px;
  gap: 8px; /* 减小间距 */
}

.publish-author {
  color: var(--td-text-color-placeholder);
  font-size: 1rem;
  text-align: center; /* 居中对齐 */
  word-wrap: break-word; /* 允许长单词换行 */
  word-break: break-all; /* 强制换行 */
  max-width: 100%; /* 最大宽度限制 */
  line-height: 1.4; /* 增加行高 */
}

.publish-time {
  color: var(--td-text-color-placeholder);
  font-size: 1rem;
  text-align: center; /* 居中对齐 */
  word-wrap: break-word; /* 允许长单词换行 */
  word-break: break-all; /* 强制换行 */
  max-width: 100%; /* 最大宽度限制 */
  line-height: 1.4; /* 增加行高 */
}

.create-time {
  color: var(--td-text-color-placeholder);
  font-size: 1rem;
  text-align: center; /* 居中对齐 */
  word-wrap: break-word; /* 允许长单词换行 */
  word-break: break-all; /* 强制换行 */
  max-width: 100%; /* 最大宽度限制 */
  line-height: 1.4; /* 增加行高 */
}

.guide-btns {
  text-align: center;
}

/* 外层自适应，填满整个容器宽度，两侧留边距 */
.rich-text-demo {
  width: 100%;
  height: auto;
  margin: 30px auto 30px auto; /* 居中显示 */
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  padding: 0 0px;
}

/* 手机壳自适应 - 放大填满容器 */
.demo-phone {
  width: 100%;
  height: auto;
  aspect-ratio: 375 / 812; /* 保持宽高比 */
  position: relative;
  background: transparent;
  overflow: hidden;
  border-radius: 60px;
  box-shadow: 0 0 16px var(--td-shadow-2, #e0e0e0); /* 使用主题阴影色 */
  display: flex;
  align-items: center;
  justify-content: center;
  /* 设置最大宽度为容器的90%，确保两侧有边距 */
  max-width: 90%;
  margin: 0 auto;
}

/* 手机壳图片自适应 */
.phone-frame-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
}

/* 屏幕内容区域自适应 */
.demo-phone-content {
  position: absolute;
  top: 8%;
  left: 4%;
  width: 92%;
  height: 85%;
  z-index: 2;
  background: transparent;
  overflow: hidden;
  border-radius: 32px;
  box-shadow: none;
}

/* iframe 填满内容区 */
.demo-phone-content .iframe {
  width: 100%;
  height: 100%;
  border: none;
  background: transparent;
}
</style>
